#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "matrix_utils.h"

// 矩阵乘法
double** Twice() {
    double **result = NULL;
    char continueInput[100];

    do {
        int rowsA, colsA;
        printf("请输入矩阵 A 的行数和列数（用空格分隔）：");
        if (scanf("%d %d", &rowsA, &colsA) != 2) {
            printf("输入无效，请输入有效的整数。\n");
            while (getchar() != '\n');
            continue;
        }
		while (getchar() != '\n');
        int rowsB, colsB;
        printf("请输入矩阵 B 的行数和列数（用空格分隔）：");
        if (scanf("%d %d", &rowsB, &colsB) != 2) {
            printf("输入无效，请输入有效的整数。\n");
            while (getchar() != '\n');
            continue;
        }
        while (getchar() != '\n');
        // 判断
        if (colsA != rowsB) {
            printf("矩阵 A 的列数必须等于矩阵 B 的行数才能进行乘法运算。\n");
            continue;
        }

        // 分配结果矩阵的内存
        result = (double **)malloc(rowsA * sizeof(double *));
        if (result == NULL) {
            printf("内存分配失败\n");
            continue;
        }
        for (int i = 0; i < rowsA; i++) {
            result[i] = (double *)malloc(colsB * sizeof(double));
            if (result[i] == NULL) {
                printf("内存分配失败\n");
                for (int j = 0; j < i; j++) {
                    free(result[j]);
                }
                free(result);
                continue;
            }
            for (int j = 0; j < colsB; j++) {
                result[i][j] = 0;
            }
        }

        double **matrixA = enterMatrix(rowsA, colsA);
        while (getchar() != '\n');
        double **matrixB = enterMatrix(rowsB, colsB);
        if (matrixA == NULL || matrixB == NULL) {
            if (result != NULL) freeMatrix(result, rowsA);
            if (matrixA != NULL) freeMatrix(matrixA, rowsA);
            if (matrixB != NULL) freeMatrix(matrixB, rowsB);
            continue;
        }

        // 相乘
        for (int i = 0; i < rowsA; i++) {
            for (int j = 0; j < colsB; j++) {
                for (int k = 0; k < colsA; k++) {
                    result[i][j] += matrixA[i][k] * matrixB[k][j];
                }
            }
        }

        printf("------乘法结果----------\n");
        printMatrix(result, rowsA, colsB);

        freeMatrix(matrixA, rowsA);
        freeMatrix(matrixB, rowsB);

        printf("是否继续进行矩阵乘法？输入 y(Y) 继续，其他值退出，谢谢使用。\n");
        while (getchar() != '\n');
        fgets(continueInput, sizeof(continueInput), stdin);
        continueInput[strcspn(continueInput, "\n")] = 0;
    } while ((continueInput[0] == 'y' || continueInput[0] == 'Y') && continueInput[1] == '\0');

    return result;
}
